﻿using AutoMapper;
using B.S.BaseData.Domain;
using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Write.Application.CommandHandlers.Purchasing.Deaths
{
    public class UpdateDeathCommandHandler : IRequestHandler<UpdateDeathCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<Death> death;
        private readonly IMapper map;

        public UpdateDeathCommandHandler(IBaseRepository<Death> death, IMapper map)
        {
            this.death = death;
            this.map = map;
        }

        public async Task<ApiResult<int>> Handle(UpdateDeathCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            try
            {
                // 获取要更新的死亡记录
                var existingDeath = await death.GetByIdAsync(request.DeathId);
                
                if (existingDeath == null /*|| existingDeath.IsDeleted*/)
                {
                    res.Message = "死亡记录不存在或已删除";
                    res.Code = ApiEnum.更新失败;
                    return res;
                }

                // 使用AutoMapper将请求映射到现有实体
                map.Map(request, existingDeath);

                // 执行更新操作
                int r = await death.UpdateAsync(existingDeath);

                if (r > 0)
                {
                    res.Message = "更新成功";
                    res.Code = ApiEnum.更新成功;
                    res.data = r;
                }
                else
                {
                    res.Message = "更新失败";
                    res.Code = ApiEnum.更新失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "更新失败: " + ex.Message;
                res.Code = ApiEnum.更新失败;
            }

            return res;
        }
    }
}
